<?php

namespace App\Http\Controllers;

use App\Models\Coupon;
use App\Models\CouponType;
use App\Models\SuningApiLog;
use Illuminate\Http\Request;
use App\Jobs\SyncSuning;
use App\Common\Common;
use App\Models\Order;
use App\Models\Product;
use Exception;
use Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client;

class MyController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        return view('my.index', [
            'user' => $user,
        ]);
    }

    public function orders()
    {
        $orders = [
            1 => [],
            4 => [],
            6 => [],
            8 => [],
            9 => [],
        ];
        Order::where('user_id', Auth::id())
            ->select('orders.*', 'products.name', 'products.cover', 'products.current_price', 'products.original_price')
            ->join('products', 'products.id', '=', 'orders.product_id')
            ->get()->each(function ($model) use (&$orders) {
                $orders[$model->status][] = $model->toArray();
            });
        $orders[1] = array_merge($orders[1], $orders[4]);
        $orders[9] = array_merge($orders[1], $orders[6], $orders[8]);
        return view('my.orders', [
            'orders' => $orders,
        ]);
    }

    public function coupons(Request $request)
    {
        $user = Auth::user();
        $coupons = [
            1 => [],
            2 => [],
            3 => [],
        ];
        Log::info($user->phone);

        for ($i = 1; $i <= 3; $i++) {
            $coupons[$i] = Coupon::where("status", '=', $i)
                ->select('coupons.*', 'coupon_types.name', 'coupon_types.code')
                ->where("accepter_phone", $user->phone)
                ->join('coupon_types', 'coupon_types.code', '=', 'coupons.card_type')
                ->orderBy('coupons.id', 'desc')->get();
        }

        return view('my.coupons', [
            'coupons' => $coupons,
        ]);
    }

    public function orderCancel(Request $request)
    {
        $orderId = $request->input('order_id', '');
        return view('my.order_cancel', [
            'orderId' => $orderId,
        ]);
    }

    public function postOrderCancel(Request $request)
    {
        $orderId = $request->input('order_id', '');
        $srvNote = $request->input('srvNote', '临时有事');
        $order = Order::find($orderId);
        if (empty($order->provider_order_id)) {
            return response()->json([
                'code' => 1,
                'msg' => '订单还在处理中，请稍后重试！',
            ]);
        }
        if ($order->status != 1) {
            return response()->json([
                'code' => 1,
                'msg' => '仅未完成订单可取消！',
            ]);
        }
        $order->status = 8;
        $order->save();
        $method = 'suning.lb.orderupdate.create';
        SyncSuning::dispatch($method, [
            'vendorCode' => config('app.suning.id'), //商家编码
            'salesOrder' => $order->provider_order_id, //ASMP服务订单号
            'updateMode' => '02', //修改类型 01：修改 02：取消
            'srvNote' => $srvNote, //修改/取消原因
            // 'serviceTime' => '', //服务预约时间
            // 'operateUser' => '' //帮客联保账号?
        ], $order->id);
        return response()->json([
            'code' => 0,
            'msg' => ' ',
        ]);
    }

    public function couponOrderCreate(Request $request)
    {
        return view('my.coupon_order_create', [
            'coupon_code' => $request->input('coupon_code', ''),
            'coupon_name' => $request->input('coupon_name', ''),
            'coupon_id' => $request->input('coupon_id', ''),
        ]);
    }

    public function couponOrderSave(Request $request)
    {
        // TODO: 将表单数据存储到我们的数据库
        // 校验参数
        $params = [
            'name' => $request->input('fullname', ''),
            'phone' => $request->input('phone', ''),
            'home' => $request->input('home', ''),
            'remark' => $request->input('remark', ''),
            'date' => $request->input('date', ''),
            'time' => $request->input('time', ''),
            'city' => $request->input('city', ''),
            'cityCode' => $request->input('cityCode', ''),
        ];
        $validator = Validator::make($params, [
            'name' => ['required'],
            'phone' => ['required'],
            'home' => ['required'],
            'city' => ['required'],
            'date' => ['required'],
            'time' => ['required'],
        ], [
            'name.required' => '请填写姓名',
            'phone.required' => '请填写手机号码',
            'city.required' => '请选择所在城市',
            'home.required' => '请输入详细小区名称及门牌号',
            'date.required' => '请选择预约日期',
            'time.required' => '请选择预约时段',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'code' => -1,
                'msg' => $validator->messages()->first(),
            ]);
            // return back()->withInput()->with('err_msg', $validator->messages()->first());
        }
        $area = explode(' ', $request->input('city', ''));
        $areaCode = explode(' ', $request->input('cityCode', ''));
        try {
            // 修改订单消费券状态
            $coupon = Coupon::find($request->input('coupon_id', null));
            if ($coupon && $coupon->status == 1) {
                $coupon->status = 2;
                $coupon->save();

                //TODO:CouponType和Products都应该使用缓存
                $product = CouponType::where('code', $coupon->card_type)
                    ->join('products', 'products.id', '=', 'coupon_types.product_id')
                    ->first();
                if (empty($product)) {
                    return response()->json([
                        'code' => -1,
                        'msg' => '订单创建错误，请稍后重试！(未知产品)',
                    ]);
                    // return back()->withInput()->with('err_msg', '订单创建错误，请稍后重试！(未知产品)');
                }
            } else {
                return response()->json([
                    'code' => -1,
                    'msg' => '订单创建错误，请稍后重试！(未知消费券)',
                ]);
                // return back()->withInput()->with('err_msg', '订单创建错误，请稍后重试！(未知消费券)');
            }
            // 创建订单
            $order = Order::create([
                'serial_number' => Common::GetSerialNumber(),
                'user_id' => Auth::id(),
                // 'coupon_code' => $request->input('coupon_code'),
                'name' => $request->input('fullname', ''),
                'phone' => $request->input('phone', ''),
                'province' => isset($area[0]) ? $area[0] : '',
                'city' => isset($area[1]) ? $area[1] : '',
                'district' => isset($area[2]) ? $area[2] : '',
                'street' => isset($area[3]) ? $area[3] : '',
                'home' => $request->input('home', ''),
                'remark' => $request->input('remark', ''),
                'date' => $request->input('date', ''),
                'time' => $request->input('time', ''),
                'coupon_id' => $coupon->id,
                'product_id' => $product->id,
                'status' => 1,
            ]);
            // 调用第三方通知接口
            $method = 'suning.lb.createorder.create';
            $productInfo = $product->toArray();
            $productInfo['attributes'] = json_decode($productInfo['attributes'], true);
            $productInfo['attributes'] = json_decode($productInfo['attributes'], true);

            SyncSuning::dispatch($method, $this->orderDataToJobData([
                'serialNumber' => $order->serial_number,
                'name' => $params['name'],
                'phone' => $params['phone'],
                'home' => $params['home'],
                'date' => $params['date'],
                'time' => $params['time'],
                'remark' => $params['remark'],
                'extdCommodityName' => $productInfo['name'],
                'extdCmmdtyCtgry' => $productInfo['attributes']['extdCmmdtyCtgry'],
                'extdCmmdtyBand' => $productInfo['attributes']['extdCmmdtyBand'],
                'brandCode' => $productInfo['attributes']['brandCode'],
                'proName' => $productInfo['attributes']['proName'],
                'propertyCode' => isset($productInfo['attributes']['propertyCode']) ? $productInfo['attributes']['propertyCode'] : null,
                'province' => isset($area[0]) ? $area[0] : '',
                'city' => isset($area[1]) ? $area[1] : '',
                'cityCode' => isset($areaCode[1]) ? $areaCode[1] : '',
                'area' => isset($area[2]) ? $area[2] : '',
                'areaCode' => isset($areaCode[2]) ? $areaCode[2] : '',
                'street' => isset($area[3]) ? $area[3] : '',
                'streetCode' => isset($areaCode[3]) ? $areaCode[3] : '',
            ]), $order->id);
            return response()->json([
                'code' => 0,
                'msg' => '',
            ]);
        } catch (Exception $e) {
            smilify('error', '订单创建错误，请稍后重试！');
            // return back()->withInput()->with('err_msg', '订单创建错误，请稍后重试！'.$e->getMessage());
            return response()->json([
                'code' => -1,
                'msg' => '订单创建错误，请稍后重试！' . $e->getMessage(),
            ]);
        }
    }

    public function orderDataToJobData($input)
    {
        $input['time'] = explode(':', $input['time']);
        $input['time'] = isset($input['time'][0]) ? $input['time'][0] : '9';
        $input['time'] = strlen($input['time']) < 2 ? '0' . $input['time'] : $input['time'];
        $input['time'] = $input['time'] . '0000';
        return [
            'seqNo' => Common::GetSerialNumber(),
            'vendorCode' => config('app.suning.id'),
            'sourceOrderItemId' => $input['serialNumber'], //商家系统订单号
            'consignee' => $input['name'], //'高樊', //顾客姓名
            'mobPhoneNum' => $input['phone'], //'13311180918', //移动电话
            'phoneNum' => '', //固定电话
            'province' => $input['province'], //'北京',
            'city' => $input['city'], //'北京',
            'area' => $input['area'], //'朝阳区',
            'street' => $input['street'], //'劲松三区甲302',
            'address' => $input['home'], //'华腾大厦2508', //详细地址
            'cityCode' => $input['cityCode'],
            'srvAreaCode' => $input['streetCode'],
            'cmmdtyQaType' => '1', //质保标识 0：保内；1：保外
            'extdCmmdtyBand' => $input['extdCmmdtyBand'],
            'extdCmmdtyCtgry' => $input['extdCmmdtyCtgry'], //苏宁商品编码
            'extdCommodityName' => $input['extdCommodityName'], //苏宁商品名称
            'brandCode' => $input['brandCode'], //苏宁品牌编码
            'orderTime' => date("YmdHis"),
            'proName' => $input['proName'], //作业项目
            'saleDate' => date('Ymd'), //'20201116',
            'saleQty' => '1', //服务数量
            'serviceTime' => str_replace('-', '', $input['date']) . '' . $input['time'], //date("YmdHis", strtotime('+2days')), //预约时间
            'propertyCode' => isset($input['propertyCode']) && $input['propertyCode'] ? $input['propertyCode'] : (object)[], //商品属性集合?
            'srvMemo' => $input['remark'], //'测试订单' //服务订单备注?
        ];
    }

    public function orderInfo(Request $request)
    {
        $orderId = $request->input('order_id', '');
        $order = Order::find($orderId);
        $product = Product::find($order['product_id']);
        return view('my.order_info', [
            'order' => $order,
            'product' => $product,
        ]);
    }
}
